package com.chenyi.leetcode.editor.cn;

/**
 * [58]最后一个单词的长度
 * @author by chenyi
 * @className LengthOfLastWord
 * @date 2022-06-21 22:39:20
 */
public class LengthOfLastWord{
    public static void main(String[] args) {
        Solution solution = new LengthOfLastWord().new Solution();
        System.out.println(solution.lengthOfLastWord("ab"));
    }
    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int lengthOfLastWord(String s) {
        // 调用api
//        String trim = s.trim();
//        String[] s1 = trim.split(" ");
//        return s1[s1.length - 1].length();
        // 算法
        String trim = s.trim();
        int length = trim.length();
        char[] chars = trim.toCharArray();
        int index = 0;
        int size = 0;
        for (int i = length - 1; i >= 0; i--) {
            if (chars[i] == ' ') {
                index = i;
                break;
            }
        }
        if (index == 0) {
            return trim.length();
        }
        for (int i = index + 1; i < length; i++) {
            size++;
        }
        return size;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}
